package com.ogms.dge.container.modules.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ogms.dge.container.common.utils.*;
import com.ogms.dge.container.modules.common.service.DataSourceService;
import com.ogms.dge.container.modules.data.converter.ServiceConverter;
import com.ogms.dge.container.modules.data.entity.ServiceEntity;
import com.ogms.dge.container.modules.data.entity.SourceEntity;
import com.ogms.dge.container.modules.data.service.ServiceService;
import com.ogms.dge.container.modules.data.service.SourceService;
import com.ogms.dge.container.modules.data.vo.ServiceVo;
import com.ogms.dge.container.modules.fs.entity.dto.DownloadFileDto;
import com.ogms.dge.container.modules.method.controller.AbstractController;
import com.ogms.dge.container.modules.sys.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import java.io.File;
import java.net.URLEncoder;
import java.util.*;


/**
 * 数据服务
 *
 * @author Lingkai Shi
 * @email lingkai.shi@nnu.edu.cn
 * @date 2024-09-23 15:10:30
 */
@RestController
@RequestMapping("data/service")
public class ServiceController extends AbstractController {
    @Autowired
    private ServiceService serviceService;

    @Resource
    private ServiceConverter serviceConverter;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SourceService sourceService;

    @Autowired
    private DataSourceService dataSourceService;

    @Resource
    private RedisComponent redisComponent;

    @Value("${container.data.dsd}")
    private String data_dsd;

    /**
     * 列表
     */
    @CrossOrigin()
    @RequestMapping("/list")
    @ApiOperation("服务列表")
//    @RequiresPermissions("data:service:list") 应该是@RequestBody 从请求体拿参数，不是请求URL拿
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = serviceService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) throws JsonProcessingException {
        return R.ok().put("service", serviceConverter.po2Vo(serviceService.getById(id), sysUserService, sourceService, dataSourceService));
    }

    @RequestMapping("/info/uuid/{uuid}")
    public R info(@PathVariable("uuid") String uuid) throws JsonProcessingException {
        ServiceEntity service = serviceService.getOne(new QueryWrapper<ServiceEntity>().eq("uuid", uuid));

        return R.ok().put("service", serviceConverter.po2Vo(service, sysUserService, sourceService, dataSourceService));
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
//    @RequiresPermissions("data:service:save")
    public R save(@RequestBody ServiceEntity service) {
        serviceService.save(service);

        return R.ok();
    }

    @RequestMapping("/save/batch")
    public R saveBatch(@RequestParam String srcUuid, @RequestBody List<Map<String, Object>> instances) throws JsonProcessingException {
        serviceService.saveBatch(srcUuid, getUserId(), instances);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("data:service:update")
    public R update(@RequestBody ServiceEntity service) {
        serviceService.updateById(service);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("data:service:delete")
    public R delete(@RequestBody Long[] ids) {
        serviceService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 创建下载URL
     */
    @RequestMapping("/createDownloadUrl")
    public R createDownloadUrl(@RequestParam String path, @RequestParam String serviceUuid) {
        String baseUrl = serviceService.getBasePath(serviceUuid);
        File file = new File(baseUrl, path);
        if (!file.exists()) {
            return R.error("File Not Found");
        } else if (file.isDirectory()) {
            return R.error("Can not download directory");
        } else {
            // 下载码
            String code = StringTools.getRandomString(Constant.LENGTH_50);
            DownloadFileDto downloadFileDto = new DownloadFileDto();
            downloadFileDto.setDownloadCode(code);
            downloadFileDto.setFilePath(file.getAbsolutePath());
            downloadFileDto.setFileName(file.getName());

            redisComponent.saveDownloadCode(code, downloadFileDto);
            return R.ok().put("data", code);
        }
    }

    /**
     * 下载
     */
    @RequestMapping("/download/{code}")
    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String code) throws Exception {
        DownloadFileDto downloadFileDto = redisComponent.getDownloadCode(code);
        if (null == downloadFileDto) {
            return;
        }
        String filePath = downloadFileDto.getFilePath();
        String fileName = downloadFileDto.getFileName();
        response.setContentType("application/x-msdownload; charset=UTF-8");
        // IE浏览器
        if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        readFile(response, filePath);
    }

}
